/**
	httppasswd.cpp
	~~~~~~~~~~~~~~~~~~~~~~~~~


	Copyright (c) 2007-2008 <ptthippo@gmail.com>

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/
#include "../common/config.h"
#include <fstream>
#include <iostream>
#include <boost/foreach.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem/exception.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/parsers.hpp>
#include "httpuserdb.h"

#ifdef WIN32
#include <conio.h>
#endif

#define MAX_STRING_LEN 256

using namespace std;
namespace fs = boost::filesystem;
namespace po = boost::program_options;

// The following password functions is extracted from APR(Apache Portable Runtime) library
#ifdef WIN32
static char *get_password(const char *prompt)
{
    static char password[128];
    int n = 0;
    int ch;

    fputs(prompt, stderr);
    
    while ((ch = _getch()) != '\r') {
        if (ch == EOF) /* EOF */ {
            fputs("[EOF]\n", stderr);
            return NULL;
        }
        else if (ch == 0 || ch == 0xE0) {
            /* FN Keys (0 or E0) are a sentinal for a FN code */ 
            ch = (ch << 4) | _getch();
            /* Catch {DELETE}, {<--}, Num{DEL} and Num{<--} */
            if ((ch == 0xE53 || ch == 0xE4B || ch == 0x053 || ch == 0x04b) && n) {
                password[--n] = '\0';
                fputs("\b \b", stderr);
            }
            else {
                fputc('\a', stderr);
            }
        }
        else if ((ch == '\b' || ch == 127) && n) /* BS/DEL */ {
            password[--n] = '\0';
            fputs("\b \b", stderr);
        }
        else if (ch == 3) /* CTRL+C */ {
            /* _getch() bypasses Ctrl+C but not Ctrl+Break detection! */
            fputs("^C\n", stderr);
            exit(-1);
        }
        else if (ch == 26) /* CTRL+Z */ {
            fputs("^Z\n", stderr);
            return NULL;
        }
	else if (ch == 27) /* ESC */ {
            fputc('\n', stderr);
            fputs(prompt, stderr);
            n = 0;
        }
        else if ((n < sizeof(password) - 1) && !iscntrl(ch)) {
            password[n++] = ch;
            fputc('*', stderr);
        }
	else {
            fputc('\a', stderr);
        }
    }
 
    fputc('\n', stderr);
    password[n] = '\0';
    return password;
}
#endif

int password_get(const char *prompt, char *pwbuf, size_t bufsiz)
{
	int rv = 0;
	
#ifdef WIN32
	char *pw_got = get_password(prompt);
#else
	char *pw_got = getpass(prompt);
#endif

	if (!pw_got)
		return -1;
	if (strlen(pw_got) >= bufsiz)
	{
		rv = -2;
	}
	
	strncpy(pwbuf, pw_got, bufsiz);
	memset(pw_got, 0, strlen(pw_got));
	return rv;
}

int main(int argc, char** argv)
{
	po::options_description available_options("Available options");

	string username, password, filename;
	string logconfig_filename;
	
	available_options.add_options()
		("add,a", po::value<string>(&username), "add user")
		("delete,d", po::value<string>(&username), "delete user")
		("verify,v", po::value<string>(&username), "verify the password of a user")
		("list,l", "list users")
		("password,p", po::value<string>(&password), "password")
		("create,c", "create a new file")
		("file,f", po::value<string>(&filename)->default_value("passwd"), "the file to save user information")
		("help,h", "print this help message")
		;

	po::variables_map vm;
	try
	{	
		po::store(po::parse_command_line(argc, argv, available_options), vm);
	}
	catch(const exception & e)
	{
		cout << e.what() << endl;
		return 0;
	}
	po::notify(vm);

	if (vm.count("help"))
	{
		cout << available_options << endl;
		return 1;
	}

	fs::path filepath(filename);

	if(vm.count("add") > 0)
	{
		if(vm.count("delete") > 0 || vm.count("list") > 0 || vm.count("verify") > 0)
		{
			cout << "You have to specify the operation, use -h to print help" << endl;
			return 1;
		}

		if(vm.count("password") == 0)
		{
			char pwin[MAX_STRING_LEN];
			char pwv[MAX_STRING_LEN];
			size_t bufsize;

			bufsize = sizeof(pwin);
			if (password_get("New password: ", pwin, bufsize) != 0)
			{
				cout << "password too long, max: " << (unsigned int)(bufsize-1) << endl;
				return 0;
			}
			bufsize = sizeof(pwv);
			password_get("Re-type new password: ", pwv, bufsize);
			if(strcmp(pwin, pwv))
			{
				cout << "password verification failed" << endl;
				return 0;
			}
			
			password.assign(pwin);
		}
		
		HTTPUserDB db(filename);
		HTTPUser user(username, password);

		if(vm.count("create") == 0)
		{
			if(db.loadDB() == false)
			{
				cout << "cannot open user database file - " << filename.c_str() << endl;
				return 0;
			}
		}

		int e = db.addUser(user);

		switch(e)
		{
			case HTTPUserDB::SUCCESS:
				cout << "user " << username.c_str() << " is added" << endl;
				db.saveDB();
				return 1;
			case HTTPUserDB::ERROR_USEREXISTED:
				cout << "user " << username.c_str() << " exists" << endl;
				return 0;
			default:
				cout << "operation failed" << endl;
				return 0;
				
		}
		
	}
	else if(vm.count("delete") > 0)
	{
		if(vm.count("add") > 0 || vm.count("list") > 0 || vm.count("verify") > 0)
		{
			cout << "You have to specify the operation, use -h to print help" << endl;
			return 1;
		}
		
		if(fs::exists(filepath) == false)
		{
			cout << "cannot open user database file - " << filename.c_str() << endl;
			return 0;
		}

		HTTPUserDB db(filename);
		if(db.loadDB() == false)
		{
			cout << "cannot open user database file - " << filename.c_str() << endl;
			return 0;
		}

		int e = db.delUser(username);
		
		switch(e)
		{
			case HTTPUserDB::SUCCESS:
				cout << "user " << username.c_str() << " is deleted" << endl;
				db.saveDB();
				return 1;
			case HTTPUserDB::ERROR_USERNOTFOUND:
				cout << "user " << username.c_str() << " not found" << endl;
				return 0;
			default:
				cout << "operation failed" << endl;
				return 0;
		}
		
	}
	else if(vm.count("list") > 0)
	{
		if(vm.count("delete") > 0 || vm.count("add") > 0 || vm.count("verify") > 0)
		{
			cout << "You have to specify the operation, use -h to print help" << endl;
			return 1;
		}

		if(fs::exists(filepath) == false)
		{
			cout << "cannot open user database file " << filename.c_str() << endl;
			return 0;
		}

		HTTPUserDB db(filename);
		if(db.loadDB() == false)
		{
			cout << "cannot open user database file " << filename.c_str() << endl;
			return 0;
		}

		vector<string> users = db.getAllUsername();
		BOOST_FOREACH(string s, users)
		{
			cout << s.c_str() << endl;
		}

		return 1;
		
	}
	else if(vm.count("verify") > 0)
	{
		if(vm.count("delete") > 0 || vm.count("add") > 0 || vm.count("list") > 0)
		{
			cout << "You have to specify the operation, use -h to print help" << endl;
			return 1;
		}

		if(fs::exists(filepath) == false)
		{
			cout << "cannot open user database file " << filename.c_str() << endl;
			return 0;
		}

		if(vm.count("password") == 0)
		{
			char pwin[MAX_STRING_LEN];
			size_t bufsize;

			bufsize = sizeof(pwin);
			if (password_get("Verify password: ", pwin, bufsize) != 0)
			{
				cout << "password too long, max: " << (unsigned int)(bufsize-1) << endl;
				return 0;
			}
			
			password.assign(pwin);
		}

		HTTPUserDB db(filename);
		if(db.loadDB() == false)
		{
			cout << "cannot open user database file " << filename.c_str() << endl;
			return 0;
		}

		int e = db.authUser(username, password);
		switch(e)
		{
			case HTTPUserDB::SUCCESS:
				cout << "password correct" << endl;
				return 1;
			case HTTPUserDB::ERROR_AUTHFAIL:
				cout << "password incorrect" << endl;
				return 0;
			case HTTPUserDB::ERROR_USERNOTFOUND:
				cout << "user " << username.c_str() << " not found" << endl;
				return 0;
			default:
				cout << "operation failed" << endl;
				return 0;
		}
	}
	else
	{
		cout << "You have to specify the operation, use -h to print help" << endl;
		return 1;
	}

	
	return 1;
}

